package com.yiboshi.rehrs.helper;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.benmanes.caffeine.cache.Cache;
import com.yiboshi.rehrs.config.RehrsSystemConfig;
import com.yiboshi.rehrs.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author jack 2025/4/5
 */
@Component
@Slf4j
public class ProxyHelper {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisLocker redisLocker;

    String proxy_api = "http://proxy.siyetian.com/apis_get.html?token=AesJWLNpXU51kaJdXTqV1dNpXRz4ERjlXTn1STqFUeORVQ61EVjhXT6lUMOp2Yw0karlXTUFUe.AM3UDN1gzM0cTM&limit=2&type=0&time=&data_format=json&showTimeEnd=true";
    static String proxyIpPoolKey = "system:ip-pool";

    static Cache<String, Object> timeoutIpCache = CacheUtils.builder(4); //10秒缓存

    public static void addErrorIp(String ip){
        /*int size = timeoutIpCache.asMap().size();
        if(size>10){
            return;
        }*/

        AtomicInteger atomicInteger = (AtomicInteger)timeoutIpCache.get(ip, (k) -> {
            return new AtomicInteger(0);
        });
        atomicInteger.incrementAndGet();

    }
    //0是不存在 1其他存在
    public static int getErrorIp(String ip){
        Object ifPresent = timeoutIpCache.getIfPresent(ip);
        return ifPresent==null?0:((AtomicInteger)ifPresent).get();
    }
    public HttpHost one(){
       /* int hit = 100;
        int hour = LocalDateTime.now().getHour();
        if(hour>=18){
            hit =5;
        }else if(hour>=19){
            hit = 4;
        }
        remove();
        if(hit<10&&AperStringUtils.hitNumber(hit)){
            //有概率不使用代理
            return null;
        }*/
        remove();
        ZSetOperations<String, String> stringStringZSetOperations = stringRedisTemplate.opsForZSet();
        Set<String> strings = stringStringZSetOperations.rangeByScore(proxyIpPoolKey, System.currentTimeMillis()+1800, Long.MAX_VALUE, 0, 15);
        if(CollUtil.isEmpty(strings)){
            loadProxyByApi();
            ThreadUtil.sleep(200);
            strings = stringStringZSetOperations.rangeByScore(proxyIpPoolKey, System.currentTimeMillis()+1800, Long.MAX_VALUE, 0, 15);
        }
        if(CollUtil.isEmpty(strings)){
            return null;
        }
        List<String> hostPortList = new ArrayList<>(strings);
        String hostStr = hostPortList.get(AperStringUtils.randomNum(hostPortList.size()));
        if(getErrorIp(hostStr)>=1){
            hostPortList.remove(hostStr);
            if(hostPortList.size()==0){
                return null;
            }
            hostStr = hostPortList.get(AperStringUtils.randomNum(hostPortList.size()));
        }
        if(strings.size()<20){
            ThreadPoolUtils.submitTask(()->{
                //加载新的ip
                loadProxyByApi();
                //删已过期的
            });
        }
        String[] split = hostStr.split(":");
        return new HttpHost(split[0], Integer.valueOf(split[1]));
    }

    public void remove() {
        ThreadPoolUtils.submitTask(()->{
            ZSetOperations<String, String> stringStringZSetOperations = stringRedisTemplate.opsForZSet();
            stringStringZSetOperations.removeRangeByScore(proxyIpPoolKey,0,(new Date().getTime()+5000));
        });
    }

    String lock="loadProxyByApiT";
    public void loadProxyByApi() {

        boolean lock1 = redisLocker.tryLock(lock, 10, "1");
        if(!lock1){
            return ;
        }
        ZSetOperations<String, String> stringStringZSetOperations = stringRedisTemplate.opsForZSet();
        Long start = System.currentTimeMillis()+5000;
        Long end = start+300000;
        Long count = stringStringZSetOperations.count(proxyIpPoolKey,start ,end);
        if(count>25){
            return;
        }
        String system_proxy_api = stringRedisTemplate.opsForValue().get("system:proxy_api_t");
        system_proxy_api = StrUtils.isBlank(system_proxy_api)?proxy_api:system_proxy_api;
        JSONObject jsonObject = JsoupUtils.httpGetJSON(system_proxy_api, null);
        JSONArray jsonArray = Optional.ofNullable(jsonObject)
                .map(o -> o.getJSONArray("data"))
                .orElse(null);
        if(CollUtil.isEmpty(jsonArray)&&count<=3&&LocalDateTime.now().getMinute()>0){
            DingdingUtils.sendMessageByLocal(RehrsSystemConfig.getProfile()+"\n未获取到有效服务器","18980482041");
            return;
        }
        if(CollUtil.isEmpty(jsonArray)&&count<=5){
            log.error("未获取到有效代理服务器 jsonArray is empty");
            return;
        }

        for (Object o : jsonArray) {
            JSONObject hostJSON = (JSONObject)o;
            String ip = hostJSON.getString("ip");
            Integer port = hostJSON.getInteger("port");
            Date end_time = hostJSON.getDate("end_time");
            stringStringZSetOperations.add(proxyIpPoolKey,ip+":"+port,end_time.getTime()-10000);
        }
        //redisLocker.delLock(lock);
    }
}
